package com.example3_31rsa.demo;/*
 *@author wujinhui
 *@create ${date} ${time}        
 *@version 1.0.0
 *@码云 小白阿辉
 */

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.example3_31rsa.demo.RSA.RSADecode;
@Controller
public class TestController {
    @GetMapping("/login")
    public String test(HttpSession session ,Model model){
        Base64 base64=new Base64();
        Base64 b1=null;
            RSAObj rsaObj=new RSAObj();
        RSA rsa=new RSA();

            model.addAttribute("rsa",rsa);
            model.addAttribute("rsaObj",rsaObj);
            model.addAttribute("base64",base64);
            session.setAttribute("rsaObj",rsaObj);


        return "login";
    }
    @PostMapping("loginin")
    @ResponseBody
    public Map<String,Object> loginin(HttpServletRequest request, HttpSession session){
        RSAObj rsaObj=(RSAObj)session.getAttribute("rsaObj");

        byte[] midbytes=null;
                String isoString= request.getParameter("password");

               try {
                 //    midbytes = new TestController().toByteArray(isoString);
                  //  midbytes=isoString.getBytes("UTF8");
                    //midbytes=
                //   System.out.print(midbytes.length);
                   midbytes= Base64.decodeBase64(isoString);
               }
               catch (Exception e){
               }
        String b=RSADecode(rsaObj.getPrivateKey(), midbytes);
               System.out.print(b);

        Map<String, Object> map = new HashMap<>();
        map.put("code",1);
         return  map;
        //  String hello=rsa.RSAEDncode(null,0, midbytes).getMessage();
      //  System.out.println(hello+"is hello");


    }




    public byte[] toByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }
}
